package concurrent.chapter01;

/**
 * @Comment:质数统计类
 * @Author:Shem
 * @Date:2019/5/25
 */
public abstract class AbstractPrimeNumberCounter {

    public static boolean isPrimeNumber(int num) {
        if (num <= 1) {
            return false;
        }
        if (num <= 3) {
            return true;
        }
        // 不在6的倍数两侧的一定不是质数
        if (num % 6 != 1 && num % 6 != 5) {
            return false;
        }
        int sqrt = (int) Math.sqrt(num);
        for (int i = 5; i <= sqrt; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }

    public static int countPrimeNumberInRange(int min, int max) {
        int count = 0;
        for (int i = min; i < max; i++) {
            if (isPrimeNumber(i)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 统计程序计算素数所花费的时间
     *
     * @param number
     */
    public void timeAndCompute(final int number) {
        final long start = System.nanoTime();
        final long numberOfPrimes = countPrimes(number);
        final long end = System.nanoTime();
        System.out.printf("Number of primes under %d is %d\n", number, numberOfPrimes);
        System.out.println("Time (seconds) taken is:" + (end - start) / 1.0e9);
    }

    public abstract int countPrimes(final int number);

}
